<?php

namespace cf;

final class String
{
      //takes arrays too
   public function __construct($data) {
      if (is_array($data)) {
         foreach ($data as $key => $val) {
            $this->data .= "$key=$val\n";
         }
      }
      else {
         $this->data = (string)$data;
      }
   }

   public function is_empty() {
      return empty($this->data);
   }

      //forward search
   public function find($what, $offset=0) {
      return strpos($this->data, $what, $offset);
   }

      //backward search
   public function rfind($what, $offset=0) {
      return strrpos($this->data, $what, $offset);
   }

   public function replace($old, $new) {
      $this->data = str_replace($old, $new , $this->data);
      return $this->data;
   }

   public function prepend($prefix, $ifItExist=false) {
      if ((0 !== $this->find($prefix)) || $ifItExist) {
         $this->data = $prefix . $this->data;
      }
      return $this->data;
   }

   static public function append($s, $postfix)
   {
      $pos = strrpos($s, $postfix);
      if ($pos !== false && strlen($postfix) == (strlen($s)-$pos)) {
         return $s;
      }
      return $s.$postfix;
   }
   
	static public function lastWord($s, $delim=' ')
	{                                              
		$s = rtrim($s,$delim);                      
		$pos = strrpos($s,$delim);                  
		if ($pos === false) {                       
			$pos = 0;                                
		}                                           
		else {                                      
			++$pos;                                  
		}                                           
		return substr($s, $pos);                    
	}                                              

   public function __toString() {
      return $this->is_empty() ? '' : $this->data;
   }

   private $data = '';
};
?>